package 链表;

public class 相交链表 {

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }

        int l1 = 1;
        ListNode node = headA;
        while (node.next != null) {
            node = node.next;
            l1++;
        }
        int l2 = 1;
        node = headB;
        while (node.next != null) {
            node = node.next;
            l2++;
        }
        if (l1 > l2) {
            for (int i = 0; i < l1 - l2; i++) {
                headA = headA.next;
            }
        } else {
            for (int i = 0; i < l2 - l1; i++) {
                headB = headB.next;
            }
        }

        while (headA != null && headB != null) {
            if (headA == headB) {
                return headA;
            } else {
                headA = headA.next;
                headB = headB.next;
            }
        }
        return null;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
